package com.kingbook.services;

import com.google.common.collect.Lists;
import com.kingbook.core.base.SupportService;
import com.kingbook.core.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Map;

import static com.kingbook.common.constant.Status.YES;

/**
 * @Author Bucky
 * @Date 2020-03-13 17:42:48
 * @Version 1.0
 */
@Slf4j
@Service
public class FinanceService extends SupportService {

    @Autowired
    WorkorderService workorderService;

    @Autowired
    PartnerService partnerService;

    @PostConstruct
    private void init() {
        setNamespace("Finance");
    }

    public JSONResult remove(int id, int type, int mid) {
        JSONResult jr = super.remove(id, mid);
        if (jr.isSuccess() && jr.getCount() == 1) {
            jr = workorderService.updateToUnReceipt(id, type, mid);
        }
        return jr;
    }

    @Transactional
    public JSONResult updateReceipt(Map<String, Object> param) {
        JSONResult jr;
        ArrayList oids = (ArrayList) param.getOrDefault("orderIds", Lists.newArrayList());
        param.put("orderNum", oids.size());
        int mid = MapUtils.getIntValue(param, "mid");
        int id = MapUtils.getIntValue(param, "id");
        int type = MapUtils.getIntValue(param, "type");
        boolean isCustomer = MapUtils.getBoolean(param, "isCustomer");
        int oid = MapUtils.getIntValue(param, "ownerId");
        if (isCustomer) {
            param.put("cid", oid);
            param.put("status", YES);
        } else {
            param.put("pid", oid);
            param.put("status", partnerService.isSystemPartner(oid, mid) ? 0 : 1);
        }
        if (id > 0) {
            jr = modify(param);
            if (jr.isSuccess() && jr.getCount() == 1 && oids.size() > 0) {
                jr = workorderService.updateToReceipt(id, type, mid, oids);
            }
        } else {
            jr = insertReturnKey("insert", param);
            if (jr.isSuccess() && oids.size() > 0) {
                id = Integer.parseInt(jr.getMsg());
                jr = workorderService.updateToReceipt(id, type, mid, oids);
            }
        }
        return jr;
    }

}
